package com.googlecode.connectlet.crypto;

import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.security.KeyFactory;
import java.security.KeyPair;
import java.security.KeyPairGenerator;
import java.security.KeyStore;
import java.security.Signature;
import java.security.cert.Certificate;
import java.security.cert.CertificateFactory;
import java.security.interfaces.RSAPrivateCrtKey;
import java.security.interfaces.RSAPublicKey;

import javax.crypto.Cipher;

import com.googlecode.connectlet.crypto.EasyProvider;
import com.googlecode.connectlet.crypto.ProviderFactory;
import com.googlecode.connectlet.crypto.rsa.provider.CompactKeySpec;
import com.googlecode.connectlet.crypto.rsa.provider.RSACipher;

public class TestProvider {
	private static final char[] KEYSTORE_PASSWORD = "changeit".toCharArray();

	public static void main(String[] args) throws Exception {
		Certificate cert = CertificateFactory.getInstance("X509").generateCertificate(new FileInputStream("D:\\CA.CER"));

		KeyPair keyPair = KeyPairGenerator.getInstance("RSA", EasyProvider.getInstance()).generateKeyPair();
		byte[] encodedPublic = keyPair.getPublic().getEncoded();
		KeyStore keyStore = KeyStore.getInstance("Compact", EasyProvider.getInstance());
		keyStore.load(null, null);
		keyStore.setKeyEntry("", keyPair.getPrivate(), KEYSTORE_PASSWORD, new Certificate[] {cert});
		FileOutputStream out = new FileOutputStream("D:\\KEYSTORE.DAT");
		keyStore.store(out, KEYSTORE_PASSWORD);
		out.close();

		KeyFactory keyFactory = KeyFactory.getInstance("RSA", EasyProvider.getInstance());
		RSAPublicKey publicKey = (RSAPublicKey) keyFactory.generatePublic(new CompactKeySpec(encodedPublic));
		FileInputStream in = new FileInputStream("D:\\KEYSTORE.DAT");
		keyStore.load(in, KEYSTORE_PASSWORD);
		in.close();
		RSAPrivateCrtKey privateKey = (RSAPrivateCrtKey) keyStore.getKey("", KEYSTORE_PASSWORD);

		byte[] data = "0123456789ABCDEF".getBytes();
		Cipher rsaCipher = ProviderFactory.generateCipher(new RSACipher());
		rsaCipher.init(Cipher.ENCRYPT_MODE, publicKey);
		byte[] cipher = rsaCipher.doFinal(data);
		rsaCipher.init(Cipher.DECRYPT_MODE, privateKey);
		System.out.write(rsaCipher.doFinal(cipher));
		System.out.println();

		Signature signature = Signature.getInstance("MD5withRSA", EasyProvider.getInstance());
		signature.initSign(privateKey);
		signature.update(data);
		byte[] sigBytes = signature.sign();
		signature.initVerify(publicKey);
		signature.update(data);
		System.out.println(signature.verify(sigBytes));
	}
}